package controller

import (
	"blog/database"
	"blog/middleware"
	"blog/model/base"
	"blog/model/user"
	"blog/router"
	"blog/types"
	"blog/utils"
	"github.com/gin-gonic/gin"
)

var userCtrl *_userController

type _userController struct {
	types.Codes
	user.AkUser
}

func init() {

	userCtrl = &_userController{}

	router.Router.POST("/user/register", userCtrl.register)

	router.Router.POST("/user/login", userCtrl.login)

	router.Router.GET("/user/list", middleware.JWT(), userCtrl.list)

	router.Router.PUT("/user/edit", middleware.JWT(), userCtrl.edit)

}

func (userCtrl *_userController) login(c *gin.Context) {

	userDto := struct {
		UserName string `json:"username" binding:"required" msg:"请输入用户名"`
		Password string `json:"password" binding:"required" msg:"请输入密码"`
	}{}

	err := c.ShouldBindJSON(&userDto)

	if nil != err {

		utils.Errors(c, err)

	}

	var userName = userDto.UserName

	var akUser = userCtrl.AkUser

	database.GetDB().Table(userCtrl.TableName()).Where("username = ?", userName).Find(&akUser)

	if akUser.ID == 0 {

		utils.Error(c, 400, "用户名或者密码不匹配")
	} else {

		var password = userDto.Password

		var newpassword = akUser.Password

		var passwordMd5 = utils.MD5(password)

		if passwordMd5 == newpassword {

			token, _ := utils.GenerateToken(akUser.ID, akUser.Username, types.StausConstant.Admin)

			utils.Success(c, gin.H{"token": token, "user": akUser})

		} else {

			utils.Error(c, 400, "用户名或者密码不匹配")

		}

	}

}

func (userCtrl *_userController) edit(c *gin.Context) {

	var idsDelete []struct {
		Id         int64  `json:"id"`
		ActiveFlag int8   `json:"activeFlag"`
		Password   string `json:"password"`
		Deleted    int8   `json:"deleted"`
	}

	err := c.ShouldBindJSON(&idsDelete)

	if nil != err {

		utils.Error(c, 400, err.Error())
		return
	}

	for i := 0; i < len(idsDelete); i++ {

		database.GetDB().Table(userCtrl.TableName()).Where("id = ?", idsDelete[i].Id).Updates(map[string]interface{}{"deleted": idsDelete[i].Deleted, "active_flag": idsDelete[i].ActiveFlag})

	}

	utils.Success(c, nil)

}

func (userCtrl *_userController) list(c *gin.Context) {

	var params = struct {
		types.Pagination
		Name string `json:"name"`
	}{}

	var users []user.AkUser

	c.ShouldBindJSON(&params)

	err := database.GetDB().Table(userCtrl.TableName()).Limit(params.Limit).Offset(params.Page).
		Where("deleted = 0 ").Order(params.Sort).Find(&users).Error

	var total int64

	database.GetDB().Table(userCtrl.TableName()).Count(&total)

	if err == nil {

		utils.SuccessList(c, users, total)

	} else {

		utils.Error(c, 400, err.Error())

	}

}

func (userCtrl *_userController) register(c *gin.Context) {

	userDto := struct {
		UserName string `json:"username" binding:"required"`
		Password string `json:"password" binding:"required"`
		Email    string `json:"email"   binding:"required"`
	}{}

	c.ShouldBindJSON(&userDto)

	var existUser = userCtrl.AkUser

	database.GetDB().Table(userCtrl.TableName()).Where("username = ? or email = ? ", userDto.UserName, userDto.Email).Find(&existUser)

	if existUser.ID > 0 {

		utils.Error(c, 400, "该账号已注册")

		return

	}

	var time, _ = types.ParseNow()

	base := base.BaseModel{CreateTime: time}

	akUser := user.AkUser{
		BaseModel:  base,
		Username:   userDto.UserName,
		Email:      userDto.Email,
		Password:   utils.MD5(userDto.Password),
		ActiveFlag: 1,
		Deleted:    0,
	}

	restul := database.GetDB().Table(userCtrl.TableName()).Create(&akUser)

	if restul.Error != nil {

		utils.Error(c, 400, restul.Error.Error())

	} else {

		utils.Success(c, akUser)
	}

}
